package com.example.demo.service.impl;

import java.lang.reflect.Field;
import java.util.List;
import java.util.Optional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.util.StringUtils;

import com.example.demo.service.BaseService;

public class BaseServiceImpl<T> implements BaseService<T>{

	@Autowired
	protected MongoRepository<T, String> mongoRepository;
	
	@Override
	public List<T> findAll() {
		return mongoRepository.findAll();
	}

	@Override
	public void save(T entity) {
		
		mongoRepository.save(entity);
	}

	@Override
	public Page<T> findAll(Pageable pageable) {
		return mongoRepository.findAll(pageable);
	}

	@Override
	public List<T> findAll(Example<T> example) {
		return mongoRepository.findAll(example);
	}

	@Override
	public List<T> findAll(Example<T> example, Sort sort) {
		return mongoRepository.findAll(example, sort);
	}

	@Override
	public Page<T> findAll(Example<T> example, Pageable pageable) {
		return mongoRepository.findAll(example, pageable);
	}

	@Override
	public Optional<T> findOne(Example<T> example) {
		return mongoRepository.findOne(example);
	}

	@Override
	public List<T> findAll(Sort sort) {
		return mongoRepository.findAll(sort);
	}

	@Override
	public Iterable<T> findAllById(Iterable<String> ids) {
		return mongoRepository.findAllById(ids);
	}

	@Override
	public Optional<T> findById(String id) {
		return mongoRepository.findById(id);
	}
	@Override
	public void updateNotNull(T entity) throws Exception{
		Object id = new Object();
		try {
			Field declaredField = entity.getClass().getDeclaredField("_id");
			declaredField.setAccessible(true);
			id = declaredField.get(entity);
		} catch (Exception e1) {
			throw new Exception("无法获取主键");
		}
		Optional<T> userOptional = mongoRepository.findById(id.toString());
		T user = userOptional.get();
		Field[] fields = user.getClass().getDeclaredFields();
		for(int i=0;i<fields.length;i++) {
			Field field = fields[i];
			field.setAccessible(true);
			String fieldName = field.getName();
			if("serialVersionUID".equals(fieldName) || "_id".equals(fieldName) || "id".equals(fieldName)) {
				continue;
			}
			try {
				Object fieldValue = field.get(entity);
				System.out.println("...fieldName = "+fieldName+"，value="+fieldValue);
				if(!StringUtils.isEmpty(fieldValue)) {
					field.set(user, fieldValue);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			
		}
		
		mongoRepository.save(user);
	}

}
